﻿/*
 * Created by SharpDevelop.
 * User: tdptcj
 * Date: 07/11/2011
 * Time: 4:51
 * 
 * To change this template use Tools | Options | Coding | Edit Standard Headers.
 */
using System;
using System.IO;
using System.Linq;
using System.Xml.Serialization;

namespace MetaVideoEditorEvolved.Engine
{
	/// <summary>
	/// Description of GenresMappingManager.
	/// </summary>
	public static class GenresMappingManager
	{
		private static string genresFile = System.IO.Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.CommonApplicationData), @"Metavideoeditorevolved\Localization\GenresMapping.xml");
		public static GenresMapping mappingTable;
		private static XmlSerializer xs = new XmlSerializer(typeof(GenresMapping));
		
		static GenresMappingManager()
		{
			if (File.Exists(genresFile)) {
				using (StreamReader sr = new StreamReader(genresFile))
				{
					mappingTable = xs.Deserialize(sr) as GenresMapping;
				}
			}
			else
			{
				mappingTable = new GenresMapping();
				mappingTable.GenreMapping = new GenresMappingGenreMapping[0];
			}
		}
		
		public static string MapGenre(string genreToMap, string videoType)
		{							
			var foundGenre = (from genre in mappingTable.GenreMapping
			                  where genre.Original.ToUpper() == genreToMap.ToUpper()
			                  && (genre.VideoType == "All" || genre.VideoType == videoType)
			                  select genre).FirstOrDefault();			
			
			if (foundGenre!=null) {
				return foundGenre.Mapped;
			}
			
			// Genre not found we will add it to the table
			var genres = mappingTable.GenreMapping.ToList();
			genres.Add(new GenresMappingGenreMapping()
			           {
			           	Original = genreToMap,
			           	Mapped = genreToMap,
			           	VideoType = videoType
			           });
			mappingTable.GenreMapping = genres.ToArray();
			
			SaveMappingTable();
			
			return genreToMap;
		}
		
		public static void SaveMappingTable()
		{
			using (StreamWriter sw = new StreamWriter(genresFile))
			{
				xs.Serialize(sw, mappingTable);
			}
		}
	}
}
